package com.example.techstudy.service;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.example.techstudy.properties.MyDataSourceProperties;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.stereotype.Service;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author: ls
 * @since: 2022/6/10
 */
@Service
public class SecondDataSourceService implements InitializingBean {

    @Autowired
    private MyDataSourceProperties properties;

    private DataSource dataSource;

    @Override
    public void afterPropertiesSet() throws Exception {
        dataSource = DruidDataSourceFactory.createDataSource(BeanMap.create(properties));
        // demo
        Connection connection = dataSource.getConnection();
        PreparedStatement ps = connection.prepareStatement("select version()");
        ResultSet rs = ps.executeQuery();
        while (rs.next()){
            String version = rs.getString(1);
            System.out.println(version);
        }
        rs.close();
        ps.close();
        connection.close();

    }
}
